package cn.linstudy.product.exception;

import cn.linstudy.common.exception.BizCodeEnume;
import cn.linstudy.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description 处理controller层的异常
 * @Date 2023/1/13
 * @Author XiaoLin
 */
@Slf4j
@RestControllerAdvice(basePackages = "cn.linstudy.product.controller") // 处理哪个包下的异常
public class MallControllerException {

    /**
     * 只能处理MethodArgumentNotValidException这个异常类
     * @param e 异常类
     * @return JSON对象
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handInvalidFiledException(MethodArgumentNotValidException e){
        Map<String,String> data = new HashMap<>();
        // 获取数据校验信息
        BindingResult bindingResult = e.getBindingResult();

        bindingResult.getFieldErrors().forEach((item)->{
            // 封装错误类对象
            data.put(item.getField(),item.getDefaultMessage());
            log.error("数据校验出现异常{}，异常类型{}",item.getField(),item.getDefaultMessage());
        });
         return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",data);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        log.error("出现异常{}",throwable.getMessage());
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}
